/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.workflow.util;


import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.swan.bean.MessageBean;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

/**
 * 指定url发送post和get请求，并放回数据
 */
public class HttpRequestGetAndPostUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpRequestGetAndPostUtil.class);

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url    发送请求的URL
     * @param params 请求参数
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, Map params) {
        BufferedReader in = null;
        StringBuffer result = new StringBuffer();
        try {
            if (params != null && !params.isEmpty()) {
                Set<Map.Entry> entries = params.entrySet();
                int size = entries.size();
                int count = 0;
                StringBuffer sb = new StringBuffer("?");
                for (Map.Entry entry : entries) {
                    sb.append(entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8));
                    count++;
                    if (count != size) {
                        sb.append("&");
                    }
                }
                url += sb.toString();
            }
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            logger.error("发送GET请求出现异常," + url + "\n"+e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage(),e);
            }
        }
        return result.toString();
    }

    /**
     * 向指定 URL 发送POST方法的请求:对象接收参数
     *
     * @param strURL     发送请求的 URL
     * @param jsonParams 请求参数,json字符串
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String strURL, String jsonParams) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        HttpPost httpPost = new HttpPost(strURL);
        try {
            httpClient = HttpClients.createDefault();
            ContentType contentType = ContentType.create("application/json", StandardCharsets.UTF_8);
            HttpEntity httpEntity = new StringEntity(jsonParams, contentType);
            // 通过setEntity 将我们的entity对象传递过去
            httpPost.setEntity(httpEntity);
            httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(),e);
        } catch (ClientProtocolException e) {
            logger.error(e.getMessage(),e);
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage(),e);
            }
        }
        return new Gson().toJson(MessageBean.create(-1, strURL + " 请求错误", String.class));
    }

    /**
     * 向指定 URL 发送POST方法的请求:字符串接收参数
     *
     * @param strURL 发送请求的 URL
     * @param params 请求参数
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String strURL, Map params) {
        BufferedReader reader = null;
        OutputStreamWriter out = null;
        try {
            if (params != null && !params.isEmpty()) {
                Set<Map.Entry> entries = params.entrySet();
                int size = entries.size();
                int count = 0;
                StringBuffer sb = new StringBuffer("?");
                for (Map.Entry entry : entries) {
                    sb.append(entry.getKey() + "=" + entry.getValue());
                    count++;
                    if (count != size) {
                        sb.append("&");
                    }
                }
                strURL += sb.toString();
            }
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // post请求必须设置为true
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            // connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            String line;
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage(),e);
            }
        }
        return new Gson().toJson(MessageBean.create(-1, strURL + " 请求错误", String.class));
    }
}
